package com.estronger.shopmanage.ui.order.until;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.estronger.shopmanage.bean.StringBean;
import com.estronger.shopmanage.ui.order.activity.OrderEntryActivity;
import com.estronger.shopmanage.ui.order.adapter.SelectActionAdapter;
import com.estronger.shopmanage.ui.order.adapter.SelectHousesAdpter;
import com.estronger.shopmanage.ui.order.adapter.TaoCanAdapter;
import com.estronger.shopmanage.ui.order.adapter.TaoCanShuxAdapter;
import com.estronger.shopmanage.ui.order.bean.BitmapItem;
import com.estronger.shopmanage.ui.order.bean.DefaultShopBean;
import com.estronger.shopmanage.ui.order.bean.NumBean;
import com.estronger.shopmanage.ui.order.bean.OrderAttributeBean;
import com.estronger.shopmanage.ui.order.bean.TaocanBean;
import com.estronger.shopmanage.ui.order.bean.TaocanitemBean;
import com.estronger.shopmanage.ui.order.bean.TaocanshuxBean;
import com.estronger.shopmanage.ui.order.bean.returnMsgEntity;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by DingYG on 2017-07-25.
 */

public class Tools {
    public static final int REQUEST_CODE_CHOISE_AGE = 79;
    public static final int REQUEST_CODE_CHOISE_ACTION = 80;
    public static final int REQUEST_CODE_CHOISE_MEALTYPE = 81;
    public static final int REQUEST_CODE_CHOISE_COLOR = 82;

    public static final int REQUEST_CODE_CHOISE_REGION = 84;
    public static final int REQUEST_CODE_CHOISE_HOUSES = 85;
    public static final int REQUEST_CODE_CHOISE_SERIZES = 86;
    public static final int REQUEST_CODE_CHOISE_STYLES = 87;
    public static final int REQUEST_CODE_CHOISE_TEXTURE = 88;
    public static final int REQUEST_CODE_CHOISE_GATHERINGTYPE = 89;

    public static final int REQUEST_CODE_CHOISE_TAOCANOTHERSHUX = 189;
    public static final int REQUEST_CODE_CHOISE_CUSTOMRES = 190;

    public static int canSNum = 99;//还可以选择的相片数量

    public static DefaultShopBean dShop;//门店默认是省市区
    public static OrderAttributeBean sCity = null;//选中的城市
    public static OrderAttributeBean sCountry = null;//选中的区县
    public static OrderAttributeBean sAction = null;//选中的活动
    public static TaocanBean sTaocan = null;//选中的套餐
    public static TaocanitemBean sOneTao = null;//选中的套餐的某个
    public static String sYjazdate = null;//预计安装时间

    public static OrderAttributeBean sKit = null;//选中的系列
    public static OrderAttributeBean sStyle = null;//选中的款式

    public static Map<String, ArrayList<TaocanitemBean>> titemMap = new HashMap<>();//某个套餐的所有属性集合
    public static Map<String, TaocanshuxBean> sTcShuMap = new HashMap<>();//选中的某个套餐的某个属性的子属性集合

    public static Map<String, Integer> indexMap;//预订单查询各状态下Fragment的页数
    public static Map<String, Integer> countMap;//预订单查询各状态下Fragment的列表总页数
    public static Map<String, Integer> pmIndexMap;//测量派工各状态下Fragment的页数
    public static Map<String, Integer> pmCountMap;//测量派工各状态下Fragment的列表总页数
    public static int LastPost = -1;//跳转到详情页的Item的id
    public static ArrayList<String> mSelectPaths = new ArrayList<>();

    public static boolean isFromShowPh = false;

    // 从资源中获取Bitmap
    public static Bitmap getBitmapFromResources(Context act, int resId) {
        Resources res = act.getResources();
        return BitmapFactory.decodeResource(res, resId);
    }

    public static String ToString(String strN) {
        if (strN == null || strN.equals("null")) {
            return "";
        } else {
            return strN;
        }
    }

    public static String ToDefaultString(String strN) {
        try {
            if (strN == null || strN.equals("")) {
                return "0";
            } else {
                return strN;
            }
        } catch (Exception e) {
            return "0";
        }
    }

    public static int ToDefaultInt(String strN) {
        if (strN == null || strN.equals("")) {
            return 0;
        } else {
            return Integer.parseInt(strN);
        }
    }

    /**
     * 根据日期返回formatter
     **/
    public static String getDateFromFormatter(String date) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date d = dateFormat.parse(date);//取时间
            return dateFormat.format(d);
        } catch (Exception e) {
            return date;
        }
    }

    /**
     * 响应头
     **/
    public static returnMsgEntity jsonResolve_returnMsgEntity(String jsonStr) throws JSONException {
        JSONObject o = new JSONObject(jsonStr);
        returnMsgEntity rm = new returnMsgEntity();
        rm.setSuccess(Boolean.valueOf(o.getString("success")));
        rm.setMsgcode(o.getString("msgcode"));
        rm.setMsg(o.getString("msg"));
        rm.setDataJson(o.getString("data"));
        return rm;
    }

    /**
     * Map2Json
     */
    public static String map2json(Map<String, String> sMap) {
        if (sMap == null) {
            return null;
        }
        Gson gson = new Gson();
        String jsonStr = gson.toJson(sMap);
        return jsonStr;
    }

    /**
     * Map2Json
     */
    public static String mapValue_2json(Map<String, String> sMap) {
        if (sMap == null || sMap.size() == 0) {
            return "";
        }
        ArrayList<Map<String, String>> sList = new ArrayList<>();
        for (Map.Entry<String, String> entry : sMap.entrySet()) {
            Map<String, String> nMap = new HashMap<>();
            nMap.put("path", entry.getValue());
            sList.add(nMap);
        }
        Gson gson = new Gson();
        String jsonStr = gson.toJson(sList);
        return jsonStr;
    }

    /**
     * List_2json
     */
    public static String List_2json(ArrayList<StringBean> sList) {
        Gson gson = new Gson();
        String jsonStr = gson.toJson(sList);
        return jsonStr;
    }

    /*
     *List<Map<>>转换成json
     *@param list
     * @return
     */
    public static String ListmapToJSON(List<Map<String, String>> list) throws
            JSONException {
        if (null == list || list.size() == 0) {
            return null;
        }
        Gson gson = new Gson();
        String jsonStr = gson.toJson(list);
        return jsonStr;

    }

    /**
     * 获取门店默认市区
     */
    public static DefaultShopBean getDefaultShopData(String result) {

        DefaultShopBean dShop = null;
        try {
            returnMsgEntity re = Tools.jsonResolve_returnMsgEntity(result);
            if (re != null) {
                if (re.getSuccess()) {
                    JSONObject o = new JSONObject(re.getDataJson());
                    dShop = new DefaultShopBean();
                    dShop.setProvinceid(Tools.ToString(o.getString("provinceid")));
                    dShop.setProvincename(Tools.ToString(o.getString("provincename")));
                    dShop.setCityid(Tools.ToString(o.getString("cityid")));
                    dShop.setCityname(Tools.ToString(o.getString("cityname")));
                    dShop.setDistrictid(Tools.ToString(o.getString("districtid")));
                    dShop.setDistrictname(Tools.ToString(o.getString("districtname")));
                }
            }
            return dShop;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取响应的数据并跳转（两个属性值）
     */
    public static ArrayList<OrderAttributeBean> getResponseData(String result, String
            field1, String field2) {
        ArrayList<OrderAttributeBean> attList = new ArrayList<OrderAttributeBean>();
        try {
            returnMsgEntity re = Tools.jsonResolve_returnMsgEntity(result);
            if (re != null) {
                if (re.getSuccess()) {
                    JSONArray r = new JSONArray(re.getDataJson());
                    if (r != null && r.length() != 0) {
                        for (int i = 0; i < r.length(); i++) {
                            JSONObject o = r.getJSONObject(i);
                            OrderAttributeBean attB = new OrderAttributeBean();
                            attB.setAttId(Tools.ToString(o.getString(field1)));
                            attB.setAttName(Tools.ToString(o.getString(field2)));
                            attList.add(attB);
                        }
                    }
                }
            }
            return attList;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取响应的数据并跳转（四个属性值）
     */
    public static ArrayList<OrderAttributeBean> getResponseData(String result,
                                                                String field1, String field2, String field3, String field4) {
        ArrayList<OrderAttributeBean> attList = new ArrayList<OrderAttributeBean>();
        try {
            returnMsgEntity re = Tools.jsonResolve_returnMsgEntity(result);
            if (re != null) {
                if (re.getSuccess()) {
                    JSONArray r = new JSONArray(re.getDataJson());
                    if (r != null && r.length() != 0) {
                        for (int i = 0; i < r.length(); i++) {
                            JSONObject o = r.getJSONObject(i);
                            OrderAttributeBean attB = new OrderAttributeBean();
                            attB.setAttId(Tools.ToString(o.getString(field1)));
                            attB.setAttName(Tools.ToString(o.getString(field2)));
                            attB.setAffiliatedid(Tools.ToString(o.getString(field3)));
                            attB.setAffiliatedName(Tools.ToString(o.getString(field4)));
                            attList.add(attB);
                        }
                    }
                }
            }
            return attList;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取各状态预订单的数量
     */
    public static NumBean getOrderNum(String result) {
        try {
            NumBean numB = new NumBean();
            returnMsgEntity re = Tools.jsonResolve_returnMsgEntity(result);
            if (re != null) {
                if (re.getSuccess()) {
                    JSONObject r = new JSONObject(re.getDataJson());
                    if (r != null) {
                        numB.setUnReceive(ToDefaultInt(r.getString("unshoprevnum")));
                        numB.setUnMeasure(ToDefaultInt(r.getString("unmeasurenum")));
                        numB.setUndeal(ToDefaultInt(r.getString("undealnum")));
                        numB.setUndeliver(ToDefaultInt(r.getString("undelivenum")));
                        numB.setUnistall(ToDefaultInt(r.getString("unistnum")));
                    }
                }
            }
            return numB;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取套餐的数据并跳转（套餐属性列表）
     */
    public static ArrayList<TaocanBean> getTaocanData(String result) {
        ArrayList<TaocanBean> atList = new ArrayList<TaocanBean>();
        try {
            returnMsgEntity re = Tools.jsonResolve_returnMsgEntity(result);
            if (re != null) {
                if (re.getSuccess()) {
                    JSONArray r = new JSONArray(re.getDataJson());
                    if (r != null && r.length() != 0) {
                        for (int i = 0; i < r.length(); i++) {
                            JSONObject o = r.getJSONObject(i);
                            TaocanBean attB = new TaocanBean();
                            attB.setTcId(Tools.ToString(o.getString("activitysuiteid")));
                            attB.setTcName(Tools.ToString(o.getString("activitysuitename")));
                            String props = o.getString("props");
                            JSONArray pr = new JSONArray(props);
                            ArrayList<TaocanitemBean> taList = new ArrayList<>();
                            for (int j = 0; j < pr.length(); j++) {
                                JSONObject oo = pr.getJSONObject(j);
                                TaocanitemBean ta = new TaocanitemBean();
                                ta.setAttId(Tools.ToString(oo.getString("activitysuitepropitemid")));
                                ta.setAttName(Tools.ToString(oo.getString("propertyname")));
                                ta.setAttVaule(null);
                                taList.add(ta);
                            }
                            attB.setTcsxList(taList);
                            atList.add(attB);
                        }

                    }
                }
            }
            return atList;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取套餐的数据并跳转（套餐的某个属性的子属性列表）
     */
    public static ArrayList<TaocanshuxBean> getTcChildData(String result) {
        ArrayList<TaocanshuxBean> shuxList = new ArrayList<TaocanshuxBean>();//用于存储
        try {
            returnMsgEntity re = Tools.jsonResolve_returnMsgEntity(result);
            if (re != null) {
                if (re.getSuccess()) {
                    JSONArray r = new JSONArray(re.getDataJson());
                    if (r != null && r.length() != 0) {
                        for (int i = 0; i < r.length(); i++) {
                            JSONObject o = r.getJSONObject(i);
                            TaocanshuxBean attB = new TaocanshuxBean();
                            attB.setProid(Tools.ToString(o.getString("propertyid")));
                            attB.setProcode(Tools.ToString(o.getString("propertycode")));
                            attB.setCode(Tools.ToString(o.getString("code")));
                            attB.setCodeid(Tools.ToString(o.getString("codeid")));
                            attB.setCodename(Tools.ToString(o.getString("codename")));
                            shuxList.add(attB);
                        }
                    }
                }
            }
            return shuxList;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 展示弹出框列表(Houses)
     */
    public static void showPopList(final Activity mContext, ArrayList<
            OrderAttributeBean> attList, ListView listView, final String ItemOnClikMsg) {
        try {
            final SelectHousesAdpter orderAdpter = new SelectHousesAdpter(mContext, attList);
            listView.setAdapter(orderAdpter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //获取到需要传回的数据后 ，绑定在跳转的intent上
                    OrderAttributeBean result = orderAdpter.getItem(position);
                    Intent intent = new Intent(mContext, OrderEntryActivity.class);
                    intent.putExtra(ItemOnClikMsg, result);
                    mContext.setResult(Activity.RESULT_OK, intent);//Result_OK 表示结果响应成功
                    mContext.finish();
                }
            });
        } catch (Exception e) {
        }
    }

    /**
     * 展示弹出框列表(Action)
     */
    public static void showActionPopList(final Activity mContext, ArrayList< OrderAttributeBean> attList, String checkedId,
                                         ListView listView, final String ItemOnClikMsg, final boolean showInMiddle) {
        try {
            final SelectActionAdapter orderAdpter = new SelectActionAdapter(mContext, attList);
            if (showInMiddle) {
                orderAdpter.setShowInMiddle(true);
            }
            orderAdpter.setCheckedId(checkedId);
            listView.setAdapter(orderAdpter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //获取到需要传回的数据后 ，绑定在跳转的intent上
                    OrderAttributeBean result = orderAdpter.getItem(position);
                    Intent intent = new Intent(mContext, OrderEntryActivity.class);
                    intent.putExtra(ItemOnClikMsg, result);
                    mContext.setResult(Activity.RESULT_OK, intent);//Result_OK 表示结果响应成功
                    mContext.finish();
                }
            });
        } catch (Exception e) {
        }
    }

    /**
     * 展示弹出框列表(套餐属性列表)
     */
    public static void showPopList_Tc(final Activity mContext, ArrayList<
            TaocanBean> tcAttList, ListView listView) {
        try {
            final TaoCanAdapter orderAdpter = new TaoCanAdapter(mContext, tcAttList);
            listView.setAdapter(orderAdpter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //获取到需要传回的数据后 ，绑定在跳转的intent上
                    TaocanBean result = orderAdpter.getItem(position);
                    Intent intent = new Intent(mContext, OrderEntryActivity.class);
                    intent.putExtra("SELECT_TAOCAN", result);
                    mContext.setResult(Activity.RESULT_OK, intent);//Result_OK 表示结果响应成功
                    mContext.finish();
                }
            });
        } catch (Exception e) {
        }
    }

    /**
     * 展示弹出框列表(套餐的某个属性的子属性列表)
     */
    public static void showPopList_TcItem(final Activity mContext, ArrayList<
            TaocanshuxBean> shuxList, ListView listView) {
        try {
            final TaoCanShuxAdapter adpter = new TaoCanShuxAdapter(mContext, shuxList);
            listView.setAdapter(adpter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //获取到需要传回的数据后 ，绑定在跳转的intent上
                    TaocanshuxBean result = adpter.getItem(position);
                    Intent intent = new Intent(mContext, OrderEntryActivity.class);
                    intent.putExtra("TAOCANSHUX_SELECT", result);
                    mContext.setResult(Activity.RESULT_OK, intent);//Result_OK 表示结果响应成功
                    mContext.finish();
                }
            });
        } catch (Exception e) {
        }
    }

    /**
     * 移除上传不成功的照片
     */
    public static List<BitmapItem> removeFailPhotos
    (List<BitmapItem> totalList, Map<String, String> failMap) {
        List<BitmapItem> arrList = totalList;
        for (int i = 0; i < arrList.size(); i++) {
            if (isExistInMap(arrList.get(i).getbPath(), failMap)) {
                arrList.remove(i);
            }
        }
        return arrList;
    }

    private static boolean isExistInMap(String sValue, Map<String, String> map) {
        boolean falg = false;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey().equals(sValue)) {
                falg = true;
                break;
            }
        }
        return falg;
    }

    public static void setEndableToRl(final RelativeLayout rlfSelect) {
        if (rlfSelect != null) {
            rlfSelect.setEnabled(false);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    rlfSelect.setEnabled(true);
                }
            }, 1000);
        }
    }

    public static void setEndableToListV(final ListView lvf) {
        if (lvf != null) {
            lvf.setEnabled(false);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    lvf.setEnabled(true);
                }
            }, 1000);
        }
    }

    /*是否是手机号码*/
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches() || (mobiles.contains("-") && mobiles.length() == 12);
    }

    public static void initIndexMap() {
        if (indexMap == null) {
            indexMap = new HashMap<>();
        }
        indexMap.put("0", 1);
        indexMap.put("1", 1);
        indexMap.put("2", 1);
        indexMap.put("3", 1);
        indexMap.put("4", 1);
        indexMap.put("5", 1);
    }

    public static void initpmIndexMap() {
        if (pmIndexMap == null) {
            pmIndexMap = new HashMap<>();
        }
        pmIndexMap.put("0", 1);
        pmIndexMap.put("1", 1);
        if(pmCountMap == null){
            pmCountMap = new HashMap<>();
        }
        pmCountMap.put("0", 1);
        pmCountMap.put("1", 1);
    }

    public static void setListViewHeightBasedOnChildren(GridView listView, int column,
                                                        int Multiple) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = column;// listView.getNumColumns();
        int totalHeight = 0;
        View listItem = listView.getChildAt(0);
        if (listItem != null) {
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight = listItem.getHeight() * Multiple;
        }
        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        //  ((ViewGroup.MarginLayoutParams) params).setMargins(1,1, 1, 1);
        // 设置参数
        listView.setLayoutParams(params);
    }

    public static void setDListViewHeightBasedOnChildren(GridView listView, int column,
                                                         int Multiple) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = column;// listView.getNumColumns();
        int totalHeight = 0;
        View listItem = listView.getChildAt(0);
        if (listItem != null) {
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight = listItem.getHeight() * Multiple;
        } else {
            totalHeight = 140 * Multiple;
        }
//        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        //  ((ViewGroup.MarginLayoutParams) params).setMargins(1,1, 1, 1);
        // 设置参数
        listView.setLayoutParams(params);
    }

    //获取当前时间

    /**
     * yyyy年MM月dd日hh:mm:ss
     * yyyy年MM月
     **/
    public static String getSystime(String formattime) {
        String systime;
        SimpleDateFormat dateFormat = new SimpleDateFormat(formattime);
        systime = dateFormat.format(new Date(System.currentTimeMillis()));
        return systime;
    }

    //文件拷贝
    //要复制的目录下的所有非子目录(文件夹)文件拷贝
    public static int CopySdcardFile(String fromFile, String toFile) {
        try {
            InputStream fosfrom = new FileInputStream(fromFile);
            OutputStream fosto = new FileOutputStream(toFile);
            byte bt[] = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
            }
            fosfrom.close();
            fosto.close();
            return 0;
        } catch (Exception e) {
            return -1;
        }
    }


}
